package com.mzy.linear_struct.面试150题;

import java.util.LinkedList;

/**
 * @Author: mizy3
 * @Date: 2024/08/16/下午3:42
 * @Description:
 */
public class Pro19删除链表的倒数第N个结点 {



    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(-1, head);
        ListNode nOfPrev = dummy;
        ListNode ans = dummy;
        while (n > 0) {
            dummy = dummy.next;
            n--;
        }

        while (dummy.next != null && nOfPrev != null) {
            dummy = dummy.next;
            nOfPrev = nOfPrev.next;
        }

        nOfPrev.next = nOfPrev.next.next;
        return ans.next;
    }
}
